import Actor from "./Actor";
import { asyncAll,guid } from "../../core/utils";
let _actors=null;
class Dispatcher{
    constructor(){
        this.id=guid();
        this.currentActor=0; 
        if(!_actors){
            _actors=[];
            for(let i=0;i<4;i++){
                let actor=new Actor();
                _actors.push(actor);
            }
        }
    }
    static instance(){
        if(!this._instance){
            this._instance=new Dispatcher();
        }
        return this._instance;
    }
    broadcast(message,callback){
        callback = callback || function () {};
        asyncAll(_actors, (actor, done) => {
            actor.send(message,done);
        }, callback);
    }
    /**
     * 
     * @param {*} message  format {type:"",data:""}
     * @param {*} callback 
     * @param {*} done 
     */
    send(message,callback,done){
        callback=callback||function(){};
        done=done||function(){};
        if(Array.isArray(message)){
            let len=message.length; 
            const results = new Array(len);
            for(let i=0;i<len;i++){
                let msg=message[i];
                this.getActor().send(msg,function(e){
                    callback(e);
                    results.push(e);
                    len--;
                    if(len==0){
                        done(results);
                    }
                });
            }
        }else{
            this.getActor().send(message,function(e){
                callback(e);
                done(e);
            });
        }
    }
    getActor(){
        this.currentActor = (this.currentActor + 1) % _actors.length;
        return _actors[this.currentActor];
    }
}
export {Dispatcher};